package minaClient;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
 
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
 
/**
 * @description
 * @date：(2015-11-29 上午9:58:30)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class UdpClient {
	
	private InetSocketAddress inetSocketAddress;
	
	private IoSession session;
	
	private IoConnector connector;
	
	public UdpClient() {
		super();
	}
	
	public UdpClient(String host,int port){
		
		inetSocketAddress=new InetSocketAddress(host,port);
		
	}
	
	public static void main(String[] args) {
		
		UdpClient udpClient=new UdpClient("115.159.58.87",9000);
		udpClient.setConnector(new NioDatagramConnector());
		udpClient.getConnector().setHandler(new ClientIoHandler());
		IoConnector connector=udpClient.getConnector();
		connector.getFilterChain().addLast("codec", 
				new ProtocolCodecFilter(
						new TextLineCodecFactory(
								Charset.forName("UTF-8"), 
								LineDelimiter.WINDOWS.getValue(),
								LineDelimiter.WINDOWS.getValue())));
		
		ConnectFuture connectFuture=connector.connect(udpClient.getInetSocketAddress());
		// 等待是否连接成功，相当于是转异步执行为同步执行。
		connectFuture.awaitUninterruptibly();
		//连接成功后获取会话对象。如果没有上面的等待，由于connect()方法是异步的，
		//connectFuture.getSession(),session可能会无法获取。
		udpClient.setSession(connectFuture.getSession());
		udpClient.getSession().write("Hello，UDPServer!");
		
	}
	
 
	public IoSession getSession() {
		return session;
	}
 
	public void setSession(IoSession session) {
		this.session = session;
	}
 
	public IoConnector getConnector() {
		return connector;
	}
 
	public void setConnector(IoConnector connector) {
		this.connector = connector;
	}
 
	public InetSocketAddress getInetSocketAddress() {
		return inetSocketAddress;
	}
 
	public void setInetSocketAddress(InetSocketAddress inetSocketAddress) {
		this.inetSocketAddress = inetSocketAddress;
	}
	
}